package com.thinking.dubbo.config;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * @ClassName MybatisPlusConfig
 * @Description TODO
 * @Author tangsixiang@gmail.com
 * @Date 2023/6/3 14:07
 * @Version 1.0
 */

@Configuration
@Slf4j
public class MybatisPlusConfig {


    /**
     * 存放动态库业务
     */
    private  String multTable="game.mult.table";

    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();

        dynamicTableNameInnerInterceptor.setTableNameHandler((sql, tableName) -> {
            System.out.println("  TtlThreadUtil.getThreadLocal().get() = " +   TtlThreadUtil.getThreadLocal().get());
            // 获取参数方法
            if(ObjectUtil.equals("CN_TW",TtlThreadUtil.getThreadLocal().get())){
                return tableName;
            }
            if(redisTemplate.opsForHash().hasKey(multTable,tableName)){
                return  redisTemplate.opsForHash().get(multTable,tableName).toString();
            }
            return tableName;
        });
        interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);

            //多租户插件
            interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
                @Override
                public Expression getTenantId() {
                    String s = TtlThreadUtil.getThreadLocal().get();
                    return new StringValue(s);
                }
                // 这是 default 方法,默认返回 false 表示所有表都需要拼多租户条件
                @Override
                public boolean ignoreTable(String tableName) {
                    return redisTemplate.opsForHash().hasKey(multTable,tableName)&&ObjectUtil.equals("CN_TW",TtlThreadUtil.getThreadLocal().get());
                }
            }));


        return interceptor;
    }

}
